做 iOS
开发时这个功能很常用, 在 OC
和 Swift
中都可以很轻松实现,因为系统本来就提供了用于日志输出的预处理宏,只要我们拿来拼接就可以了,但是在 Dart
中并不提供这些,那有什么办法实现它呢?
+
一、思考
做 iOS
开发时这个功能很常用, 在 OC
和 Swift
中都可以很轻松实现,因为系统本来就提供了用于日志输出的预处理宏,只要我们拿来拼接就可以了,但是在 Dart
中并不提供这些,那有什么办法实现它呢?
我们回想在开发过程中,是不是发现只要一不小心抛异常,就可以看到类似如下的打印内容,而且还能清楚的知道异常是在哪个文件和哪一行的代码造成的。

所以如果我们可以在调用函数时拿到当前调用堆栈,就可以取到一系列想要的数据。
二、实践
在 dart:core
中提供了 堆栈跟踪(StackTrace)
,可以通过 StackTrace.current
取到当前的堆栈信息,打印如下图所示,会发现这不好拿到我们想要的信息。

这里我用到了官方开发的一个包 stack_trace,它可以将堆栈信息变得更多人性化,并方便我们查看堆栈信息和获取想要的数据。
ps: stack_trace
在 Flutter
环境下直接导包即可使用,而在纯 Dart
下需要将其添加为依赖于pubspec.yaml
中。
1 2
| dependencies: stack_trace: ^1.9.3
|
那下面我们来试试 stack_trace 的威力吧
1 2 3 4 5 6 7 8 9 10 11 12 13
| import 'package:stack_trace/stack_trace.dart';
final chain = Chain.forTrace(StackTrace.current);
final frames = chain.toTrace().frames; final frame = frames[1];
print("所在文件:${frame.uri} 所在行 ${frame.line} 所在列 ${frame.column}");
|
三、呈上代码
下面我做了一点封装,直接拿走即可使用,打印效果如下所示:
完整的代码和示例请到GitHub上【查看】。

代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
enum FLogMode { debug, warning, info, error, }
void FLog(dynamic msg, { FLogMode mode = FLogMode.debug }) { if (kReleaseMode) { return; } var chain = Chain.current(); chain = chain.foldFrames((frame) => frame.isCore || frame.package == "flutter"); final frames = chain.toTrace().frames; final idx = frames.indexWhere((element) => element.member == "FLog"); if (idx == -1 || idx+1 >= frames.length) { return; } final frame = frames[idx+1];
var modeStr = ""; switch(mode) { case FLogMode.debug: modeStr = "💚 DEBUG"; break; case FLogMode.warning: modeStr = "💛 WARNING"; break; case FLogMode.info: modeStr = "💙 INFO"; break; case FLogMode.error: modeStr = "❤️ ERROR"; break; }
print("$modeStr ${frame.uri.toString().split("/").last}(${frame.line}) - $msg "); }
|